package com.xing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xing.DTO.ConferenceDTO;
import com.xing.DTO.VideoDTO;
import com.xing.Utils.MyUtils;
import com.xing.config.JSONUtils;
import com.xing.config.RedisUtils;
import com.xing.dao.ConferenceDao;
import com.xing.dao.ConferenceUserDao;
import com.xing.dao.SysUserDao;
import com.xing.entity.ConferenceEntity;
import com.xing.entity.ConferenceUserEntity;
import com.xing.entity.SysUserEntity;
import com.xing.service.ConferenceService;
import com.xing.user.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @version 1.0
 * @Author Xing
 * @Date 2024/1/16 17:02
 */
@Service
@Slf4j
public class ConferenceServiceImpl extends ServiceImpl<ConferenceDao, ConferenceEntity> implements ConferenceService {
    @Autowired
    private ConferenceDao dao;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private SysUserDao userDao;
    @Autowired
    private ConferenceUserDao conferenceUserDao;

    public QueryWrapper<ConferenceEntity> getParams(Map<String, Object> params) {
        QueryWrapper<ConferenceEntity> queryWrapper = new QueryWrapper<>();
        String name = (String) params.get("params");
        queryWrapper.like("name", name);
        queryWrapper.orderByDesc("create_date");
        return queryWrapper;
    }

    @Override
    public String create(ConferenceDTO conferenceDTO) throws Exception {
        String conCode = getConCode();
        conferenceDTO.setConCode(conCode);
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        conferenceDTO.setCreator(principal.getId());
        conferenceDTO.setCreateDate(new Date());
        boolean save = save(JSONUtils.objParse(conferenceDTO, ConferenceEntity.class));
        if (save) {
            return conCode;
        } else {
            return "error";
        }
    }

    @Override
    public IPage<ConferenceEntity> Page(Map<String, Object> params) {
        QueryWrapper<ConferenceEntity> queryWrapper = getParams(params);
        Page<ConferenceEntity> conferenceEntityPage = new Page<>();
        IPage<ConferenceEntity> page = page(conferenceEntityPage, queryWrapper);
        return page;
    }

    @Override
    public Object into(ConferenceDTO dto) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("con_code", dto.getConCode());
        ConferenceDTO conferenceEntity = dao.GetOne(dto.getConCode());
        User principal = (User) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        try {
            if (conferenceEntity.getConPassword().equals(dto.getConPassword())) {
                return conferenceEntity;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void Delete(String id) {
        ConferenceDTO conferenceEntity = dao.GetOne(id);
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        redisUtils.hdel("room:" + conferenceEntity.getId(), "user:" + principal.getId());
        ConferenceUserEntity conferenceEntity1 = conferenceUserDao.getConferenceEntity(conferenceEntity.getId(), principal.getId());
        conferenceEntity1.setLeaveDate(new Date());
        conferenceUserDao.updateById(conferenceEntity1);
    }

    @Override
    public String commit(ConferenceDTO conferenceDTO) {
        User principal = (User) SecurityContextHolder
                .getContext().getAuthentication().getPrincipal();
        ConferenceDTO conferenceDTO1 = dao.GetOne(conferenceDTO.getConCode());
        redisUtils.hset("room:" + conferenceDTO1.getId(),
                "user:" + principal.getId(), conferenceDTO.getRtcInfo());
        Integer conference = conferenceUserDao.
                getConference(conferenceDTO1.getId(), principal.getId());
        if (conference == 0) {
            ConferenceUserEntity conferenceUserEntity =
                    new ConferenceUserEntity(principal.getId(),
                            conferenceDTO1.getId(), 0, new Date());
            conferenceUserDao.insert(conferenceUserEntity);
        }
        return conferenceDTO.getConCode();
    }

    @Override
    public List<VideoDTO> GetVideoList(String roomId) {
        List<VideoDTO> videos = new ArrayList<>();
        ConferenceDTO conferenceDTO = dao.GetOne(roomId);
        User principal = (User) SecurityContextHolder
                .getContext().getAuthentication().getPrincipal();
        Map map = redisUtils.hgetMap("room:" + conferenceDTO.getId());
        for (Object o : map.keySet()) {
            String key = o.toString();
            String userId = o.toString().replace("user:", "");
            if (!userId.equals(principal.getId().toString())) {
                SysUserEntity sysUserEntity = userDao.selectById(userId);
                VideoDTO videoDTO = new VideoDTO();
                videoDTO.setOffer(map.get(key));
                videoDTO.setName(sysUserEntity.getUsername());
                //videoDTO.setHeadUrl(sysUserEntity.getHeadUrl());
                videoDTO.setUserId(sysUserEntity.getId());
                videos.add(videoDTO);
            }
        }
        return videos;
    }

    public String getConCode() {
        String code01 = UUID.randomUUID().toString().substring(0, 3);
        String code02 = UUID.randomUUID().toString().substring(0, 4);
        String code03 = UUID.randomUUID().toString().substring(0, 3);
        return code01 + "-" + code02 + "-" + code03;
    }
}
